from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

class Notification(models.Model):
    """系统通知模型"""
    
    # 优先级选择
    PRIORITY_CHOICES = (
        ('low', '低'),
        ('medium', '中'), 
        ('high', '高'),
    )
    
    # 目标角色选择（与用户模型保持一致）
    ROLE_CHOICES = (
        ('admin', '管理员'),
        ('technician', '维修技术人员'),
        ('customer', '客户'),
        ('receptionist', '前台'),
        ('quality_checker', '质检员'),
        ('all', '所有用户'),
    )
    
    title = models.CharField(max_length=200, verbose_name='通知标题')
    content = models.TextField(verbose_name='通知内容')
    target_roles = models.CharField(max_length=100, verbose_name='目标角色')
    created_by = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        verbose_name='创建者',
        related_name='created_notifications'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    start_date = models.DateTimeField(default=timezone.now, verbose_name='开始时间')
    end_date = models.DateTimeField(verbose_name='结束时间')
    priority = models.CharField(
        max_length=10, 
        choices=PRIORITY_CHOICES, 
        default='medium', 
        verbose_name='优先级'
    )

    class Meta:
        verbose_name = '系统通知'
        verbose_name_plural = '系统通知'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.title} - {self.get_target_roles_display()}"

    def get_target_roles_display(self):
        """获取目标角色的显示名称"""
        # 处理不同的存储格式
        target_roles_str = self.target_roles
        
        # 如果存储的是列表格式的字符串，如 "['customer', 'receptionist']"
        if target_roles_str.startswith('[') and target_roles_str.endswith(']'):
            # 移除方括号和引号，然后分割
            cleaned_str = target_roles_str[1:-1].replace("'", "").replace('"', '')
            roles = [role.strip() for role in cleaned_str.split(',')]
        else:
            # 处理逗号分隔的字符串
            roles = [role.strip() for role in target_roles_str.split(',')]
        
        display_names = []
        for role in roles:
            for code, name in self.ROLE_CHOICES:
                if code == role.strip():
                    display_names.append(name)
                    break
        return ', '.join(display_names) if display_names else '无'

    def is_current(self):
        """检查通知是否在当前有效期内"""
        now = timezone.now()
        return self.is_active and self.start_date <= now <= self.end_date

    def get_priority_class(self):
        """获取优先级的CSS类名"""
        return {
            'high': 'danger',
            'medium': 'warning', 
            'low': 'info'
        }.get(self.priority, 'info')
